package com.hmdp.utils;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    /*生成开始时间戳*/
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    /*序列号的位数*/
    private static final int CONT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /*生成全局的唯一ID*/
    public long nextId(String keyPrefix) {

        //生成时间戳
        LocalDateTime time = LocalDateTime.now();
        long nowSecond = time.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond-BEGIN_TIMESTAMP;
        //生成序列号
        String date = time.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        //拼接并返回
        return timeStamp << CONT_BITS | count;//先向左移动32位，再进行或运算
    }


}
